import Vue from 'vue'
import Vuex from 'vuex'
import { axios } from '../plugins/axios'

Vue.use(Vuex)

function getItem (key, result = null) {
  try {
    return JSON.parse(localStorage.getItem(key));
  } catch {
    return result;
  }
}

export default new Vuex.Store({
  state: {
    user: getItem('user'),
    token: null,
    sys: getItem('sys'),
    loading: 0,
    alarm: getItem('alarm', false)
  },
  mutations: {
    setAlarm (state, alarm) {
      localStorage.setItem('alarm', alarm)
      state.alarm = alarm
    },
    setLoginInfo (state, { user, sys, token }) {
      localStorage.setItem('user', JSON.stringify(user))
      localStorage.setItem('sys', JSON.stringify(sys))
      localStorage.setItem('token', token)
      state.user = user
      state.sys = sys
    },
    setUser (state, user) {
      localStorage.setItem('user', JSON.stringify(user))
      state.user = user
    },
    setUserAttr (state, { key, val }) {
      state.user[key] = val
      localStorage.setItem('user', JSON.stringify(state.user))
    },
    setSys (state, sys) {
      localStorage.setItem('sys', JSON.stringify(sys))
      state.sys = sys
    },
    clearUser (state) {
      localStorage.removeItem('user')
      localStorage.removeItem('sys')
      localStorage.removeItem('token')
      state.user = null
      state.sys = null
      state.token = null
    },
    loadingAdd (state) {
      state.loading++
    },
    loadingSub (state) {
      setTimeout(() => {
        state.loading--
      }, 200)
    }
  },
  actions: {
    pullUser ({ state }) {
      axios.get('/me')
        .then(res => {
          const user = res.data.data
          localStorage.setItem('user', JSON.stringify(user))
          state.user = user
          //console.log(state.user);
        })
      // commit('increment')
    }
  },
  modules: {}
})